import { useEffect, useRef, forwardRef, useImperativeHandle } from "react";
import { useFrame, useThree } from "@react-three/fiber";
import { PerspectiveCamera } from "@react-three/drei";
import { Vector3, Euler } from "three";

// 定义摄像机相对于玩家的偏移量
const CAMERA_DISTANCE = 5;
const CAMERA_HEIGHT = 2;

export const TPV = forwardRef(({ isThirdPerson, playerPosition }, ref) => {
  const { camera, gl } = useThree();
  
  // 存储鼠标旋转状态
  const mouseRotation = useRef({ x: Math.PI / 4, y: 0 });
  
  // 存储计算出的水平旋转
  const horizontalRotation = useRef(new Euler(0, 0, 0));
  
  // 玩家前方的目标点
  const targetPosition = useRef(new Vector3());

  // 使用useImperativeHandle暴露旋转值和目标位置给父组件
  useImperativeHandle(ref, () => ({
    getRotation: () => horizontalRotation.current,
    getTargetPosition: () => targetPosition.current,
    getCameraDirection: () => {
      // 返回相机朝向的方向向量
      const direction = new Vector3();
      direction.subVectors(targetPosition.current, camera.position).normalize();
      return direction;
    }
  }));
  
  // 启用鼠标控制，不需要按下鼠标也能旋转
  const isMouseControlEnabled = useRef(true);
  
  useEffect(() => {
    // 初始化相机角度
    mouseRotation.current = { x: Math.PI / 4, y: 0 };
    
    // 鼠标移动处理函数
    const onMouseMove = (e) => {
      if (isThirdPerson && isMouseControlEnabled.current) {
        // 水平旋转 (左右) - 不再需要鼠标按下的条件
        mouseRotation.current.y -= e.movementX * 0.005;
        
        // 垂直旋转 (上下) - 加上正号实现Y轴反转
        mouseRotation.current.x = Math.max(
          0.1, // 最小角度
          Math.min(Math.PI / 2 - 0.1, mouseRotation.current.x + e.movementY * 0.005)
        );
        
        // 更新水平旋转（用于玩家移动方向）
        horizontalRotation.current.set(0, mouseRotation.current.y, 0);
      }
    };
    
    // 监听键盘事件，按C键可以切换是否启用鼠标控制
    const onKeyDown = (e) => {
      if (e.code === 'KeyC' && isThirdPerson) {
        isMouseControlEnabled.current = !isMouseControlEnabled.current;
        console.log("Mouse control:", isMouseControlEnabled.current ? "enabled" : "disabled");
      }
    };
    
    // 添加事件监听
    document.addEventListener('mousemove', onMouseMove);
    document.addEventListener('keydown', onKeyDown);
    
    return () => {
      // 清理事件监听
      document.removeEventListener('mousemove', onMouseMove);
      document.removeEventListener('keydown', onKeyDown);
    };
  }, [isThirdPerson]);
  
  // 在每一帧更新相机位置
  useFrame(() => {
    if (!isThirdPerson) return;
    
    // 计算相机偏移量 - 确保相机始终在玩家后方
    const offset = new Vector3(
      Math.sin(mouseRotation.current.y) * CAMERA_DISTANCE * Math.cos(mouseRotation.current.x),
      CAMERA_HEIGHT + CAMERA_DISTANCE * Math.sin(mouseRotation.current.x),
      Math.cos(mouseRotation.current.y) * CAMERA_DISTANCE * Math.cos(mouseRotation.current.x)
    );
    
    // 设置相机位置为玩家位置加上偏移量（相机在玩家后方）
    camera.position.copy(playerPosition).add(offset);
    
    // 计算玩家前方的点（而不是看向玩家本身）
    targetPosition.current.copy(playerPosition).sub(offset.clone().normalize().multiplyScalar(10));
    targetPosition.current.y = playerPosition.y + 0.5; // 保持视线稍微向上
    
    // 让相机看向玩家前方
    camera.lookAt(targetPosition.current);
    
    // 确保每帧都更新水平旋转
    horizontalRotation.current.set(0, mouseRotation.current.y, 0);
  });
  
  return null;
}); 